package com.sevencar.peterview;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class DataAdapter<T extends DataAdapter.AdapterData> extends RecyclerView.Adapter<ViewHolder> {

    public interface AdapterData {
        String getTitle();
        String getThumbnailUrl();
    }

    public interface OnClickListener<T> {
        void onClick(T obj);
    }

    private List<T> dataList;
    private int layoutId;
    private int imageViewId;
    private int textViewId;
    private Resources resources;
    private OnClickListener<T> listener;

    public DataAdapter(List<T> dataList, int layoutId, int imageViewId, int textViewId, int placeHolderImageId, Resources resources) {
        this.dataList = dataList;
        this.layoutId = layoutId;
        this.imageViewId = imageViewId;
        this.textViewId = textViewId;
        this.resources = resources;
    }

    public void setOnClickListener(OnClickListener<T> listener) {
        this.listener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
        return new ViewHolder(v, imageViewId, textViewId);
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int position) {
        final T data = dataList.get(position);
        viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null) {
                    listener.onClick(data);
                }
            }
        });
        viewHolder.getTextView().setText(data.getTitle());
        try {
            InputStream is = resources.getAssets().open(data.getThumbnailUrl());
            Bitmap bm = BitmapFactory.decodeStream(is);
            viewHolder.getImageView().setImageBitmap(bm);
        } catch (IOException e) {
        }
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }
    
}
